/*
 * #%L
 * Tools
 * %%
 * Copyright (C) 2011 Ractoc.com
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package com.ractoc.tools.logging;

import org.apache.log4j.Priority;
import org.apache.log4j.Logger;

import java.text.MessageFormat;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

/**
 * * A JULI (java.util.logging) handler that redirects java.util.logging
 * messages to Log4J * http://wiki.apache.org/myfaces/Trinidad_and_Common_Logging
 * * <br> * User: josh * Date: Jun 4, 2008 * Time: 3:31:21 PM
 */
public class JuliToLog4jHandler extends Handler {
    
    private static Logger logger = Logger.getLogger(JuliToLog4jHandler.class.getName());
    
    public void publish(LogRecord record) {
        org.apache.log4j.Logger log4j = getTargetLogger(record.getLoggerName());
        if (log4j != null) {
            Priority priority = toLog4j(record.getLevel());
            log4j.log(priority, toLog4jMessage(record), record.getThrown());
        } else {
            logger.warn("unable to log message: " + record);
        }
    }
    
    static Logger getTargetLogger(String loggerName) {
        logger.debug("getting logger for class " + loggerName);
        if (loggerName != null) {
            return Logger.getLogger(loggerName);
        } else {
            return null;
        }
    }
    
    public static Logger getTargetLogger(Class clazz) {
        logger.debug("getting logger for class " + clazz);
        return getTargetLogger(clazz.getName());
    }
    
    private String toLog4jMessage(LogRecord record) {
        String message = record.getMessage();
        // Format message        
        try {
            Object parameters[] = record.getParameters();
            if (parameters != null && parameters.length != 0) {
                // Check for the first few parameters ?               
                if (message.indexOf("{0}") >= 0 || message.indexOf("{1}") >= 0 || message.indexOf("{2}") >= 0 || message.indexOf("{3}") >= 0) {
                    message = MessageFormat.format(message, parameters);
                }
            }
        } catch (Exception ex) {
            // ignore Exception        
        }
        return message;
    }
    
    private org.apache.log4j.Level toLog4j(Level level) {
        //converts levels     
        if (Level.SEVERE == level) {
            return org.apache.log4j.Level.ERROR;
        } else if (Level.WARNING == level) {
            return org.apache.log4j.Level.WARN;
        } else if (Level.INFO == level) {
            return org.apache.log4j.Level.INFO;
        } else if (Level.OFF == level) {
            return org.apache.log4j.Level.OFF;
        }
        return org.apache.log4j.Level.OFF;
    }
    
    @Override
    public void flush() {
        // nothing to do  
    }
    
    @Override
    public void close() {
        // nothing to do  
    }
}
